<template>
  <div class="app-container">
    <el-drawer title="配置鞋子" :visible.sync="drawer" :with-header="false" :before-close="closeDrawer" size="50%">

      <!-- 物品类型 -->
      <MyTag title="物品类型" :itemType="itemTypeList" chooseType="single"></MyTag>

      <!-- <el-button @click="detasil">查看状态被改变得</el-button> -->

      <el-row style="padding-left: 20px;">
        <div style="font-size: 24; font-weight: 700; margin-bottom: 10px;"> 拍照</div>
        <el-col :span="16">

          <CameraCaptureTask v-if="cameraCaptureVisible" ref="cameraCaptureTask" @success="success"
            @close="cameraCaptureVisible = false" />


          <el-button style="width: 100%;" type="primary" @click="photography">拍照</el-button>

        </el-col>

        <el-col :span="6" style="margin-left: 10px;" class="imageShow">


          <el-col :span="6" v-for="(item, index) in shoeDetail.picture" :key="item.data">
            <div class="image-item">
             
              <el-image style="width: 50px; height: 50px; margin-right: 5px" :src="item.url" :preview-src-list="shoeDetail ? shoeDetail.picture.map((item) => item.url) : []
                ">
              </el-image>
               <i class="el-icon-error" @click="deleteImage(index)" />
            </div>

          </el-col>

          <el-col :span="6">
            <el-button class="image-item" size="small" type="primary" @click="handleUploadImage">上传</el-button>
          </el-col>
        </el-col>


      </el-row>


      <MyTag title="配饰" :itemType="peiShiTypeList"></MyTag>


      <MyTag title="备注" :itemType="remarkTypeList"></MyTag>

      <div style="padding-left: 20px;">
        <span style="margin-right: 15px;">选择清洗类型</span>
          <el-select v-model="washType" filterable placeholder="请选择">
              <el-option
                v-for="item in washTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
      </div>

      <div class="ywyj_drawer_footer">
        <el-button type="info" @click="closeDrawer">取消</el-button>
        <el-button type="primary" @click="sumitGoods" :loading="loading">确定</el-button>
      </div>
    </el-drawer>

  </div>
</template>

<script>
import CameraCaptureTask from "@/components/CameraCaptureTask/CameraCaptureTask.vue";
import MyTag from '@/components/MyTag'
import { v4 as uuidv4 } from "uuid";
import { getOssClient } from "../../../../utils/tool";
import dayjs from "dayjs";
import { base64DataToFile } from "@/utils/file";
import { orderInNew } from "@/api/order"
import { wupingType, peiShiType, remarkType , washTypeList } from '@/config/index'


export default {
  name: "Ywyj_drawer",
  components: {
    MyTag,
    CameraCaptureTask
  },
  props: {
    drawer: Boolean,
    washCode: String,
    shoeDetail: Object,
    detail: Object,
  },
  data() {
    return {
      washType:"",
      washTypeList,
      loading:false,
      cameraCaptureVisible: false,
      num: 0,
      itemTypeList: [],
      peiShiTypeList: [],
      uploadList:[],
      remarkTypeList: []


    };
  },
  created() {
    this.cameraCaptureVisible = true
    this.init()
     document.addEventListener("keydown", this.quckliPhoto);
     this.num=this.shoeDetail.picture? this.shoeDetail.picture.length:0
  },

  destroyed() {
    document.removeEventListener("keydown", this.quckliPhoto);
  },

  methods: {

    //兼听快捷键拍照
    quckliPhoto(event){
     
     if (event.key === "F3") {
        event.preventDefault();
        event.stopPropagation();
        this.photography()
     
      }
    },

    init() {
      this.resetChooseType()//重置选项
      //获取物品类型
      let itemType = this.shoeDetail.itemType
      this.washType=this.shoeDetail.washType
      if (itemType && itemType != '请选择物品类型') {

        this.duoxuanDetails(this.itemTypeList, itemType)
      }
      //获取配饰
      let peishi = this.shoeDetail.accessorVoList;
      if (peishi) {
        peishi.forEach(res => {
          this.duoxuanDetails(this.peiShiTypeList, res.type)
        })
      }

      //获取备注
      let remarks = this.shoeDetail.remarks
      if (remarks) {
        remarks.forEach(res => {
          this.duoxuanDetails(this.remarkTypeList, res)
        })
      }
    },


    resetChooseType() {
      this.itemTypeList = [...wupingType]
      this.peiShiTypeList = [...peiShiType]
      this.remarkTypeList = [...remarkType]
      this.itemTypeList.forEach(res => res.choose = false)
      this.peiShiTypeList.forEach(res => res.choose = false)
      this.remarkTypeList.forEach(res => res.choose = false)
    },


    sumitGoods() {
      if(!this.washType){
        this.$message.error("清洗类型不能为空！")
        return
      }
      if(this.shoeDetail.picture.length == 0){
         this.$message.error("图片至少需要拍照一个")
        return
      }
     
      // //校验图片
      let filterArr=this.shoeDetail.picture.filter(res=> res.data == "null")
      let newfilterArr=this.shoeDetail.picture.filter(res=> res.data == " ")
      let resultArr=filterArr.concat(newfilterArr)
      if(resultArr.length>0){
        this.$message.error("图片完整性校验失败！！")
        return 
      }
    

      let that = this
      delete this.shoeDetail.accessorVoList
      this.removeRepeat(this.remarkTypeList)
      this.removeRepeat(this.itemTypeList)
      this.removeRepeat(this.peiShiTypeList)
      if(!this.itemTypeList.filter(res => { if (res.choose) { return res.title } })[0]){
         this.$message.error("请选择物品类型")
         return
      }
      that.loading=true
      orderInNew({
        ... this.shoeDetail,
        remark: this.remarkTypeList? this.remarkTypeList.filter(res => { if (res.choose) { return res.title } }).map(res => { return res.title }):[],
        accessorieRecords: this.getPeiShiList(),
        itemType: this.itemTypeList.filter(res => { if (res.choose) { return res.title } })[0].title,
        shoeImgDtoList: this.shoeDetail.picture.map(res => {
          let obj = { shoeImg: res.data, shoeId: this.shoeDetail.id ? this.shoeDetail.id : this.shoeDetail.shoeId,washType:this.washType }
          return obj
        }),
        orderId: this.detail.id
      }).then(res => {
        that.loading=false
        that.$message.success("操作成功")
        that.closeDrawer()
        // console.info(res)
      })


    },



    getPeiShiList() {

      let objArr = this.peiShiTypeList.filter(res => res.choose);
      // console.info("已经找到得配饰", objArr)
      let arr = objArr.map(res => {
        if (res.choose) {
          let obj = { itemType: res.title }
          return obj
        }
      })
      // console.info("组装并且返回得配饰", arr)
      return arr;


    },


    //根据title属性去重复数据
    removeRepeat(arr) {
      //去掉数组中重复的数据在重新赋值
      let uniqueArray = arr.filter((item, index, self) => {

        return self.findIndex(i => i.title === item.title) === index;
      });
      arr = []
      arr = uniqueArray
      // console.info("去掉重复数据", arr, this.peiShiTypeList)
    },


    duoxuanDetails(arr, targetTitle) {
      let wupingIndex = arr.findIndex(res => res.title == targetTitle)
      if (wupingIndex != -1) {
        arr[wupingIndex].choose = true
      } else {
        arr.push({ title: targetTitle, choose: true })
      }
    },





    handleUploadImage() {
      /**
       * 创建input 批量上传图片
       */
      let input = document.createElement("input");
      let that=this
      input.type = "file";
      input.accept = "image/*";
      input.multiple = true;
      input.onchange = (e) => {
        // console.info("上传得图片",e.target.files)
        const files = e.target.files;
        for (let i = 0; i < files.length; i++) {
          const file = files[i];
          const reader = new FileReader();
          reader.onload = (e) => {
            that.uploadList = [];
            const url = e.target.result;
            const uuid = uuidv4();
            // console.info("上传回调")
            that.uploadList.push({
              url,
              washCode: this.washCode,
              uuid,
            });
           this.uploadImage(that.uploadList);
          };
          reader.readAsDataURL(file);
        }
      };
      input.click()
      input.remove()
      
    },



    updateShoeDetail(data) {
      this.$emit("update-shoeDetail", data)
    },

    deleteImage(index) {
      this.num = (this.num - 1)
      // console.info("num=",this.num)
      this.shoeDetail.picture.splice(index, 1);


      // if (this.shoeDetail[scopeIndex].picture.length === 0) {
      //   this.shoeDetail.splice(scopeIndex, 1);
      //   if (this.washCode === this.shoeDetail[index].washCode) {
      //     this.washCode = "";
      //   }
      // }
    },

    closeDrawer() {
      // console.info("关闭弹窗")
      this.cameraCaptureVisible = false;
      this.$emit('close-ywyj-event')

    },

    photography() {
      let num = this.num + 1
      // console.info("add_num=",this.num)
      if (this.num > 7) {
        this.$message.error('照片数量最多支持8张！！！');
        return
      }
      this.num = num
      this.$refs.cameraCaptureTask.photograph();
    },

    success(photos) {
      const shoeDetail = { picture: [] }
      const uploadList = [];
      photos.forEach((item) => {
        const uuid = uuidv4();
        // shoeDetail.picture.push({
        //   url: item,
        //   data: null,
        //   status: "upload",
        //   uuid,
        // });

        uploadList.push({
          url: item,
          washCode: shoeDetail.washCode,
          uuid,
        });
      });

      this.uploadImage(uploadList);
      // this.washCode = "";
      // this.$refs.washCodeInput.focus();
    },

    async uploadImage(waitUploadImageList) {
      // console.info("上传图片",waitUploadImageList)
      // debugger
      try {
        const client = await getOssClient();
    
        // 等待上传的图片
        const requestList = waitUploadImageList.map((item) => {
          const fileName = `public/img/${dayjs().format(
            "YYYY-MM-DD"
          )}/${uuidv4()}.png`;
          item.efficient = fileName;
          return client.put(fileName, base64DataToFile(item.url));
        });

        const resultList = await Promise.all(requestList);
       
        resultList.forEach((res, index) => {
          const imageObject = waitUploadImageList[index];
          this.shoeDetail.picture.push({
            url: imageObject.url,
            data: waitUploadImageList[index].efficient,
            status: "success",
            uuid: uuidv4(),
          })

          this.updateShoeDetail({ ... this.shoeDetail })

        });
      } catch (error) {
        console.error(error);
      }
    },
    // detasil(){
    //   console.info(this.wupingType)
    // }


  }
};
</script>

<style scoped lang="scss">
.imageShow {
  // width: 220px;
  display: flex;
  flex-wrap: wrap;

  .image-item {
    position: relative;
    flex: 0 0 50px;

    &:nth-child(4n) {
      margin-right: 0;
    }

    .el-icon-error {
      position: absolute;
      left: -4px;
      top: -4px;
      z-index: 999;
      background-color: #ffffff;
      border-radius: 50%;
      cursor: pointer;
    }
  }
}

// .image-box{
//   display: flex;
//   flex-direction: row;
//   flex-wrap: wrap;
//   // justify-content: space-between;

// }
// .image-item{
//   margin-right: 20px;
//   min-width: 100px;
//   position: relative;
//   z-index: 999;
// }
// .el-icon-error {
//   position: absolute;
//   right: 0;
//   top: 0;
//   z-index: 1;
//   background-color: #ffffff;
//   border-radius: 50%;
//   cursor: pointer;
// }
.ywyj_drawer_footer {
  margin-top: 30px;
  padding-right: 20px;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}
</style>
